<template>
  <div class="task-schedule">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>日程安排管理</span>
          <el-button type="primary" @click="handleAdd">新增日程</el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="日程标题">
          <el-input v-model="searchForm.title" placeholder="请输入日程标题" clearable />
        </el-form-item>
        <el-form-item label="日程类型" style="width: 230px;">
          <el-select v-model="searchForm.type" placeholder="请选择日程类型" clearable>
            <el-option label="会议" value="会议" />
            <el-option label="设计" value="设计" />
            <el-option label="交付" value="交付" />
            <el-option label="客户沟通" value="客户沟通" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" style="width: 230px;">
          <el-select v-model="searchForm.priority" placeholder="请选择优先级" clearable>
            <el-option label="低" value="低" />
            <el-option label="中" value="中" />
            <el-option label="高" value="高" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态"  style="width: 230px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="未开始" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="日程标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="80">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ getPriorityName(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="160" />
        <el-table-column prop="endTime" label="结束时间" width="160" />
        <el-table-column prop="location" label="地点" width="120" show-overflow-tooltip />
        <el-table-column prop="allDay" label="全天" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.allDay ? 'success' : 'info'">
              {{ scope.row.allDay ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        :title="dialogType === 'add' ? '新增日程' : '编辑日程'"
        v-model="dialogVisible"
        width="650px"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="日程标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入日程标题" />
          </el-form-item>
          <el-form-item label="日程类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择日程类型">
              <el-option label="会议" value="meeting" />
              <el-option label="设计" value="design" />
              <el-option label="交付" value="delivery" />
              <el-option label="客户沟通" value="communication" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间设置" required>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item prop="allDay">
                  <el-checkbox v-model="form.allDay">全天</el-checkbox>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item prop="timeRange">
                  <el-date-picker
                    v-model="form.timeRange"
                    :type="form.allDay ? 'daterange' : 'datetimerange'"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :default-time="form.allDay ? ['00:00:00', '23:59:59'] : undefined"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="地点" prop="location">
            <el-input v-model="form.location" placeholder="请输入地点" />
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-select v-model="form.priority" placeholder="请选择优先级">
              <el-option label="低" value="low" />
              <el-option label="中" value="medium" />
              <el-option label="高" value="high" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态">
              <el-option label="未开始" value="upcoming" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="重复设置" prop="recurrenceType">
            <el-select v-model="form.recurrenceType" placeholder="请选择重复类型">
              <el-option label="不重复" value="none" />
              <el-option label="每天" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>
          <el-form-item label="提醒时间" prop="reminderTime">
            <el-date-picker
              v-model="form.reminderTime"
              type="datetime"
              placeholder="请选择提醒时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="日程内容" prop="content">
            <el-input
              v-model="form.content"
              type="textarea"
              :rows="3"
              placeholder="请输入日程内容"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 搜索表单数据
const searchForm = reactive({
  title: '',
  type: '',
  priority: '',
  status: '',
  timeRange: [],
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const form = reactive({
  id: null,
  title: '',
  type: '',
  timeRange: [],
  location: '',
  allDay: false,
  priority: 'medium',
  status: 'upcoming',
  content: '',
  recurrenceType: 'none',
  reminderTime: null
})

// 表单校验规则
const rules = {
  title: [{ required: true, message: '请输入日程标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择日程类型', trigger: 'change' }],
  timeRange: [{ required: true, message: '请选择时间范围', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 获取日程列表
const getScheduleList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      startTime: searchForm.timeRange?.[0],
      endTime: searchForm.timeRange?.[1]
    }
    delete params.timeRange
    
    const response = await request.get('/api/designer/schedule/list', { params })
    tableData.value = response.content
    total.value = response.totalElements
  } catch (error) {
    console.error('获取日程列表失败:', error)
    ElMessage.error('获取日程列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  searchForm.pageNum = 1
  getScheduleList()
}

// 处理重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (key !== 'pageNum' && key !== 'pageSize') {
      searchForm[key] = ''
    }
  })
  searchForm.timeRange = []
  handleSearch()
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = null
  Object.keys(form).forEach(key => {
    if (key !== 'id') {
      form[key] = key === 'priority' ? 'medium' : 
                  key === 'status' ? 'upcoming' : 
                  key === 'allDay' ? false :
                  key === 'recurrenceType' ? 'none' : ''
    }
  })
  form.timeRange = []
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    if (key === 'timeRange') {
      form.timeRange = [row.startTime, row.endTime]
    } else {
      form[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该日程吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/api/designer/schedule/${row.id}`)
      ElMessage.success('删除成功')
      getScheduleList()
    } catch (error) {
      console.error('删除日程失败:', error)
      ElMessage.error('删除日程失败')
    }
  }).catch(() => {})
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = { ...form }
        data.startTime = data.timeRange[0]
        data.endTime = data.timeRange[1]
        delete data.timeRange

        if (dialogType.value === 'add') {
          await request.post('/api/designer/schedule', data)
          ElMessage.success('新增成功')
        } else {
          await request.put(`/api/designer/schedule/${data.id}`, data)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        getScheduleList()
      } catch (error) {
        console.error('保存日程失败:', error)
        ElMessage.error('保存日程失败')
      }
    }
  })
}

// 处理分页
const handleSizeChange = (val) => {
  searchForm.pageSize = val
  getScheduleList()
}

const handleCurrentChange = (val) => {
  searchForm.pageNum = val
  getScheduleList()
}

// 获取类型标签样式
const getTypeTag = (type) => {
  const map = {
    meeting: 'warning',
    design: 'success',
    delivery: 'info',
    communication: 'primary'
  }
  return map[type] || ''
}

// 获取类型名称
const getTypeName = (type) => {
  const map = {
    meeting: '会议',
    design: '设计',
    delivery: '交付',
    communication: '客户沟通'
  }
  return map[type] || type
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const map = {
    low: 'info',
    medium: 'warning',
    high: 'danger'
  }
  return map[priority] || ''
}

// 获取优先级名称
const getPriorityName = (priority) => {
  const map = {
    low: '低',
    medium: '中',
    high: '高'
  }
  return map[priority] || priority
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    upcoming: 'info',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return map[status] || ''
}

// 获取状态名称
const getStatusName = (status) => {
  const map = {
    upcoming: '未开始',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

// 初始化
onMounted(() => {
  getScheduleList()
})
</script>

<style scoped>
.task-schedule {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.el-date-editor.el-input),
:deep(.el-date-editor.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style> 